package com.bawei.module_mine.login

import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.text.InputType
import android.view.View
import androidx.activity.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_common.Router
import com.bawei.lib_common.base.BaseActivity
import com.bawei.lib_common.base.flow_eventbus.core.EventBusCore
import com.bawei.lib_common.base.state.Failed
import com.bawei.lib_common.base.state.Loading
import com.bawei.lib_common.base.state.Success
import com.bawei.lib_common.base.utils.ToastUtils

import com.bawei.lib_common.observeWithLifecycle
import com.bawei.module_mine.MineActivity
import com.bawei.module_mine.R
import com.bawei.module_mine.databinding.ActivityLoginBinding
import com.bawei.module_mine.mine.MineViewModel
import com.bawei.module_mine.model.LoginSuccessEvent
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import java.lang.reflect.Parameter


@Route(path = Router.Ui.LoginActivity)
@AndroidEntryPoint
class LoginActivity : BaseActivity<MineViewModel,ActivityLoginBinding>() {
    override val mLayoutResId: Int
        get() = R.layout.activity_login
    override val mViewModel: MineViewModel by viewModels()
    private val mHandler = Handler(Looper.getMainLooper())// 用于延迟执行任务
    // 手机号正则表达式（匹配11位，1开头，第二位3-9）
    private val PHONE_REGEX = "^1[3-9]\\d{9}$".toRegex()
    @Autowired(name = Router.Intent.EXTRA_PHONE , required = false)
    @JvmField
    var phone: String? = null

    @Autowired(name = Router.Intent.EXTRA_PASSWORD , required = false)
    @JvmField
    var password: String? = null

    override fun initView() {
        ARouter.getInstance().inject(this)
        mBinding.viewmodel = mViewModel
        mBinding.lifecycleOwner = this
        // 监听共享数据变化（可选，若需实时更新 UI）
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                // 绑定数据（自动同步）
                initAccount()
            }
        }
        initHeader()
    }
    private fun initHeader() {
        mBinding.loginHead.apply {
            loginHeadPen.visibility = View.GONE
            loginHeadHead.visibility = View.GONE
            loginHeadPlane.visibility = View.GONE
            loginHeadUsername.visibility = View.GONE
        }
    }



    override fun initListener() {
        mViewModel.requestLoginEvent.observeWithLifecycle(this, Lifecycle.State.STARTED){
            when(it){
                is Success -> {
                    setLoadingViewVisible(false)
                    //账号密码登录成功
                    ToastUtils.showLong(this@LoginActivity,"登录成功,即将跳转首页")
                    // 通过 ViewModelProvider 获取 EventBusCore 实例（确保生命周期绑定）
                    val eventBusCore = ViewModelProvider(this)[EventBusCore::class.java]
                    // 发送登录成功事件（携带用户数据）
                    eventBusCore.postEvent(eventName = "LoginSuccessEvent",  // 事件名（需唯一）
                        value = LoginSuccessEvent("欢迎回来"),               // 事件对象
                        timeMillis = 0 )
                    //延迟跳转
                    mHandler.postDelayed({
                        ARouter.getInstance().build(Router.Ui.MineActivity).navigation()
                    }, 1000)
                }
                is Loading -> {
                    setLoadingViewVisible(true)
                    //账号密码登录成功
                }
                is Failed -> {
                    setLoadingViewVisible(false)
                    ToastUtils.showLong(this@LoginActivity,"登录失败,请检查账号密码是否正确")
                }
                else ->{

                }
            }
        }
        mBinding.btnGoRegister.setOnClickListener {
            ARouter.getInstance().build(Router.Ui.RegisterActivity).navigation()
        }
        mBinding.goModifyPass.setOnClickListener {
            ARouter.getInstance().build(Router.Ui.ModifyPassActivity).navigation()
        }
    }

    override fun initData() {
        mBinding.btnLogin.setOnClickListener {
            if (mBinding.username.text.toString().trim().isBlank()){
                ToastUtils.showLong(this@LoginActivity,"手机号不可以为空")
                return@setOnClickListener
            }
            if (!mBinding.username.text?.matches(PHONE_REGEX)!!){
                ToastUtils.showLong(this@LoginActivity,"请输入正确的手机号")
                return@setOnClickListener
            }
            mViewModel.passLogin()
        }
    }
    private fun initAccount() {
//        // 填充数据（非空判断）
        phone?.let { mBinding.username.setText(it) }
        password?.let {
            mBinding.password.setText(it)
            // 可选：显示密码明文
            mBinding.password.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mHandler.removeCallbacksAndMessages(null)//  移除所有延迟任务
    }
}